import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const fetchTemplateData = (currentPage, pageSize) => {
  axios
    .post(
      "/WordTool/word/maintain/pageList",
      qs.stringify({
        currentPage,
        pageSize,
      }),
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then(
      (resp) => {
        const records = [];
        for (let i = 0; i < resp.data.records.length; i++) {
          records.push({
            uuid: resp.data.records[i].uuid,
            appid: resp.data.records[i].appid,
            code: resp.data.records[i].code,
            url: resp.data.records[i].url,
            downloadName: resp.data.records[i].downloadName,
            createTime: resp.data.records[i].createTime,
            tmExist: resp.data.records[i].tmExist,
          });
        }

        mapStore.templateTableData = records;
        mapStore.templateTableTotal = resp.data.total;
      },
      (err) => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error",
        });
      }
    );
};

const handleAjaxDelete = (scope) => {
  axios
    .post(
      "/WordTool/word/maintain/delete",
      qs.stringify({
        id: scope.row.uuid,
      }),
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      }
    )
    .then(
      (resp) => {
        if (resp.data.status === "OK") {
          ElMessage({
            message: "模板删除成功",
            type: "success",
          });

          fetchTemplateData(
            mapStore.templateTableCurrentPage,
            mapStore.templateTablePageSize
          );
        } else {
          ElMessage({
            message: resp.data.message,
            type: "error",
          });
        }
      },
      (err) => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error",
        });
      }
    );
};

export { fetchTemplateData, handleAjaxDelete };
